package com.example.forum.controller;

import com.example.forum.commen.AppResult;
import com.example.forum.commen.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @RequestParam("boardId") @NonNull Long boardId,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content) {
        // 校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            //用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //板块校验
        Board board = boardService.selectByPrimaryKey(boardId.longValue());
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            //大打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);//标题
        article.setContent(content);//正文
        article.setBoardId(boardId);//板块id
        article.setUserId(user.getId());//作者id
        //调用service
        articleService.create(article);
        //响应
        return AppResult.success();
    }
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value = "boardId",required = false) Long boardId) {
        //定义返回的集合
        List<Article> articles;
        if(boardId == null) {
            //查询所有
             articles = articleService.selectAll();
        }else {
           articles = articleService.selectAllByBoardId(boardId);

        }
        if(articles == null) {
            //结果为空，创建空集合
            articles = new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }
    /*
    * 根据帖子id获取详情
    * */
    @GetMapping("/details")
    private AppResult<Article> getDetails(HttpServletRequest request,
            @RequestParam("id") @NonNull Long id) throws JsonProcessingException {
        //从session中获取当前登录用户
        HttpSession session = request.getSession(false);
        User user =(User) session.getAttribute(AppConfig.USER_SESSION);
        //调用services获取帖子详情
        Article article = articleService.selectDetailById(id);
        //判断结果是否为空
        if(article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLENOT_EXISTS);
        }
        //判断当前用户是否是作者
        if(user.getId() == article.getUserId()) {
            //标识为作者
            article.setOwn(true);
        }

        return AppResult.success(article);
    }
    /*
    * 更新帖子
    * */
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @RequestParam("id") @NonNull Long id,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content) {
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1) {
            //返回错误，描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //
        //判断用户是否作者
        Article article = articleService.selectById(id);
        //校验帖子是否有效
        if(article == null) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLENOT_EXISTS);
        }
        //判断是否是作者
        if(user.getId() != article.getUserId()) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子状态
        if(article.getState() == 1 || article.getDeleteState() == 1) {
            //禁止访问
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //调用service
        articleService.modify(id,title,content);
        //打印日志
        log.info("帖子更新成功 Article id = "+id+" User id = "+user.getId()+"。");
        //返回正确结果
        return AppResult.success();
    }
    @PostMapping("/thumbsUp")
    private AppResult thumbsUp (HttpServletRequest request,
                                @RequestParam("id") @NonNull Long id) {
        //校验用户状态
        HttpSession session = request.getSession(false);
        User user =(User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //调用service
        articleService.thumbsUpById(id);
        //返回成功
        return AppResult.success();
    }

    //删除帖子
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @RequestParam("id") @NonNull Long id) {
        //获取session信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //用户是否禁言
        if(user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        //帖子是否存在
        if(article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLENOT_EXISTS);
        }
        //是否是作者
        if(user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用servixe
        articleService.deleteById(id);
        //返回正常
        return AppResult.success();
    }

    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request,
                                    @RequestParam(value = "userId",required = false) Long userId){
        //UserId为空,从session中获取当前登录的用户Id
        if(userId == null) {
             HttpSession session = request.getSession(false);
             User user = (User) session.getAttribute(AppConfig.USER_SESSION);
             userId = user.getId();
         }
        //调用service
        List<Article> list = articleService.selectByUserId(userId);
         return AppResult.success(list);
    }
}
